package com.ds.infrastructure.hyperspace.container.config;

import com.ds.infrastructure.hyperspace.common.config.ContainerConfig;
import com.ds.infrastructure.hyperspace.container.internal.ContainerInitException;
import com.ds.infrastructure.hyperspace.container.internal.NettyContainer;
import com.ds.infrastructure.hyperspace.monitor.config.MonitorConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author  Weishaoying
 */
@Slf4j
@EnableConfigurationProperties(ContainerProperties.class)
@Configuration
public class ContainerInitConfiguration {

    private static final String ENV_FIELD_NAME = "env";

    private static final String DEFAULT_ENV = "local";

    @Autowired
    private Environment environment;

    @Autowired
    private ContainerProperties containerProperties;

    @Autowired
    private MonitorConfiguration monitorConfiguration;

    @PostConstruct
    private void initContainer() {
        ContainerConfig containerConfig = containerProperties.getContainer();
        if (containerConfig == null) {
            log.error("Init container error, config not found!");
            throw new ContainerInitException("ContainerInitConfiguration not found");
        }
        String runtimeEnvironment = environment.getProperty(ENV_FIELD_NAME, DEFAULT_ENV);
        containerConfig.setEnv(runtimeEnvironment);
        log.info("Runtime environment is [{}]", runtimeEnvironment);
        NettyContainer container = NettyContainer.getInstance();
        container.setMetricsManager(monitorConfiguration.getMetricsManager());
        container.start(containerConfig);
    }

    @PreDestroy
    private void destroyContainer() {
        NettyContainer.getInstance().shutdown();
    }

}
